package server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPServer {

    public static ServerParam p =new ServerParam();
    public static void main(String[] args) throws IOException {
            initSocketPacket();
            for (;;) {
                receive();
                fromA("132");
                fromB("129");
                address();
            }


    }

    //两个都接收到后分别A、B址地交换互发

    private static void address() throws IOException {
        if (!p.tamsg.equals("") && !   p.tbmsg.equals("")) {
            sendA();
            sendB();
            p.tamsg = "";
            p.tbmsg = "";
        }
    }
    private static void fromB(String msg){
        if (p.rmsg.contains(msg)) {
            p.pb = p.packet.getPort();
            p.ab = p.packet.getAddress();
            p.tbmsg = "host:" +    p.ab.getHostAddress() + ",port:" +    p.pb;
        }
    }
    private static void fromA(String msg){
        //接收到clientA
        if (p.rmsg.contains(msg)) {
            p.pa = p.packet.getPort();
            p.aa = p.packet.getAddress();
            p.tamsg = "host:" +    p.aa.getHostAddress() + ",port:" +   p.pa;
        }
    }
    private static void receive() throws IOException {
        p.server.receive(p.packet);
        p.rmsg = new String(p.packet.getData(), 0, p.packet.getLength());
        System.out.println(   p.rmsg);
    }
    private static void initSocketPacket() throws SocketException {

        p.server= new DatagramSocket(p.sport);
        byte[] buf = new byte[1024];
        p.packet = new DatagramPacket(buf, buf.length);
    }

    private static void sendB() throws IOException {
            byte[] sendBuf = p.tamsg.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, p.aa, p.pa);
            p.server.send(sendPacket);
           print();
    }


    private static void sendA() throws IOException {

            byte[] sendBuf = p.tbmsg.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, p.ab, p.pb);
            p.server.send(sendPacket);
            print();

    }

    private static void print(){
        System.out.println("消息发送成功!");
    }
}